#include <func.h>

int main()
{
    //创建UDP的套接字
    int serverfd = socket(AF_INET, SOCK_DGRAM, 0);
    ERROR_CHECK(serverfd, -1, "socket");

    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8080);
    serveraddr.sin_addr.s_addr = inet_addr("192.168.30.129");

    //绑定网络地址
    int ret = bind(serverfd, 
                   (const struct sockaddr*)&serveraddr, 
                   sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "bind");

    char buff[100] = {0};
    //客户端的网络地址
    struct sockaddr_in clientaddr;
    memset(&clientaddr, 0, sizeof(clientaddr));
    socklen_t len = sizeof(clientaddr);

    //存储多个客户端的网络地址
    struct sockaddr_in clientaddrs[100] = {0};

    while(1) {
        //接收数据, 可以看到UDP协议是基于数据报的协议
        //一次sendto可以用一次recvfrom接收
        printf("before recvfrom.\n");
        //第五个参数clientaddr有可能是不同的客户端传递过来的信息
        //不一定是同一个客户端,每调用一次都会被修改
        recvfrom(serverfd, buff, sizeof(buff), 0,
                 (struct sockaddr*)&clientaddr, &len);
        printf("recv msg from client %s:%d\n",
               inet_ntoa(clientaddr.sin_addr),
               ntohs(clientaddr.sin_port));
        printf("msg: %s\n\n", buff);

        //发送数据
        const char * msg = "hello,client";
        sendto(serverfd, msg, strlen(msg), 0,
               (const struct sockaddr*)&clientaddr, len);
    }


    close(serverfd);
    return 0;
}

